package cn.asterly.cicada.web.controller;

import cn.asterly.cicada.common.utils.IPInfoUtil;
import cn.asterly.cicada.model.Log;
import cn.asterly.cicada.model.User;
import cn.asterly.cicada.service.ILogService;
import cn.asterly.cicada.service.base.BaseServiceImpl;
import cn.asterly.cicada.service.impl.LogServiceImpl;
import cn.asterly.cicada.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.UUID;

/**
 * @Author likun
 * @Description
 * @Date 13:45 2019-01-15
 **/
@Controller
public class IndexController {

    @Autowired
    public UserServiceImpl userBaseService;

    @Autowired
    private LogServiceImpl logService;

    /**
     * @Description
     * @Date 13:47 2019-01-15
     **/
    @RequestMapping("/index")
    public String index(HttpServletRequest request, HttpServletResponse response){
        String ipAddr = IPInfoUtil.getIpAddr(request);
        Log log=new Log();
        log.setId(UUID.randomUUID().toString());
        log.setLogtype("visit");
        log.setMethod("/index");
        log.setRequestip(ipAddr);
        //写入登录的城市
        if(IPInfoUtil.isInnerIp(ipAddr)){
            log.setDescription("湖北省武汉市");
        }else{
            try {
                log.setDescription(IPInfoUtil.getIpCity(ipAddr));
            } catch (Exception e) {
                log.setDescription("湖北省武汉市");
                e.printStackTrace();
            }
        }
        log.setCreatetime(new Date());
        log.setUsername("访客");
        if(logService.insertSelective(log)){
            return "404";
        }
        return "index";
    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(User user,HttpServletRequest request){
        String ipAddr = IPInfoUtil.getIpAddr(request);
        String email = user.getEmail();
        User userinfo = userBaseService.loginByEmail(email);
        if(userinfo!=null){
            if(userinfo.getEmail().equals(email)){
                if(userinfo.getPassword().equals(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()))){
                    return "redirect:swagger-ui.html";
                }
            }else{
                System.out.println("用户名错误");
            }
        }
        return "index";
    }

}
